package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

import csc.daonjpa.java.controller.EntityManagerFactoryUtil;
import csc.daonjpa.java.domain.Card;

/**
 * DAO class for Card entity. This class contains all methods that inserts/updates/deletes
 * card info
 * @author nvu3
 *
 */
@Component
public class CardDAO {
	
	/**
	 * @return all cards from Card table
	 */
	public List<Card> getCards() {
		
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		// -----------Begin transaction-----------
		List<Card> cards = null;
		try {
			entr.begin();
			// Get a list of cards from DB
			TypedQuery<Card> query = entityManager.createQuery("SELECT a FROM Card a", Card.class);
			cards = query.getResultList();
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------

		return cards;
		
	}
	
	/**
	 * Add card to Card table
	 * @param card Card entity that contains mapped with each column in Card table
	 * @return
	 */
	public boolean addCard(Card card) {
		// Obtains entity manager object
		EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager();
		
		// Obtains transaction from entity manager
		EntityTransaction entr = entityManager.getTransaction();
		
		try {
			// -----------Begin transaction-----------
			entr.begin();
			// Insert a row to Card table
			entityManager.persist(card);
			entr.commit();
		} catch (Exception e) {
			entityManager.close();
		}
		// -----------End transaction-----------
		
		return true;
	}
}
